package host.skiree.nettydemo.server.service.impl;

import host.skiree.nettydemo.message.GroupQuitRequestMessage;
import host.skiree.nettydemo.message.GroupQuitResponseMessage;
import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.impl.RoomChannelImpl;
import host.skiree.nettydemo.server.service.MessageHandler;
import io.netty.channel.ChannelHandlerContext;

import java.util.Set;

/**
 * @author gcl
 * @date 2022/9/21 9:11
 */
public class GroupQuit implements MessageHandler {
    @Override
    public void handleMessage(ChannelHandlerContext ctx, Message message) {
        GroupQuitRequestMessage groupQuitRequestMessage = (GroupQuitRequestMessage) message;
        String groupName = groupQuitRequestMessage.getGroupName();
        Set<String> users = RoomChannelImpl.ROOM_CHANNEL_MAP.get(groupName);
        if (users != null){
            String userName = groupQuitRequestMessage.getUsername();
            if ( !users.contains(userName) ){
                ctx.writeAndFlush(new GroupQuitResponseMessage(false, "您不在该聊天室,无须退出"));
            }else {
                users.remove(userName);
                if ( users.isEmpty() ){
                    RoomChannelImpl.ROOM_CHANNEL_MAP.remove(groupName);
                }else {
                    RoomChannelImpl.ROOM_CHANNEL_MAP.put(groupName, users);
                }
                ctx.writeAndFlush(new GroupQuitResponseMessage(true, "您已从聊天室 "+ groupName+" 退出"));
            }
        }else {
            ctx.writeAndFlush(new GroupQuitResponseMessage(false, "该聊天室不存在"));
        }
    }
}
